package com.seed.application.service.stat;

import com.mybatisflex.core.row.Db;
import com.seed.core.builder.datapermis.DataPermisWrapper;
import com.seed.core.builder.keyword.KeywordWrapper;
import com.seed.core.builder.search.SearchedBuilder;
import com.seed.core.builder.search.SearchedWrapper;
import com.seed.core.builder.stat.StatBuilder;
import com.seed.core.pojo.seed.Seed;
import com.seed.core.pojo.seed.Stat;
import com.seed.core.query.pojo.Declared;
import com.seed.core.query.pojo.Searched;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StatQuery {
    private final Seed seed;
    private final Map<String, Stat> stats; // 统计配置
    private String keyword; // 关键字
    private Map<String, Declared> declareds;
    private Map<String, Searched> searcheds;
    private List<Map<String, Searched>> dataPermised;

    public StatQuery(Seed seed, Map<String, Stat> stats) {
        this.seed = seed;
        this.stats = stats;
    }

    public Map<String, Object> query() {
        List<StatBuilder> statBuilders = getStatBuilders();

        Map<String, Object> ret = new HashMap<>();
        for(StatBuilder statBuilder : statBuilders) {
            Stat stat = statBuilder.getStat();
            ret.put(stat.getName(), Db.selectObject(statBuilder.build()));
        }

        return ret;
    }

    private List<StatBuilder> getStatBuilders() {
        List<StatBuilder> ret = new ArrayList<>();
        if(stats == null || stats.isEmpty()) return ret;

        for(Map.Entry<String, Stat> entry: stats.entrySet()) {
            Stat tmp = entry.getValue();
            String[] searches = tmp.getSearches();

            Map<String, Searched> statSearcheds = new HashMap<>(searcheds);
            if(searches != null) SearchedBuilder.build(statSearcheds, seed, searches);

            tmp.setName(entry.getKey());
            StatBuilder statBuilder = new StatBuilder(seed, tmp);
            statBuilder.setSearchedWrapper(new SearchedWrapper(seed, statSearcheds));
            statBuilder.setKeywordWrapper(new KeywordWrapper(seed, declareds, keyword));
            statBuilder.setDataPermisWrapper(new DataPermisWrapper(seed, dataPermised));

            ret.add(statBuilder);
        }

        return ret;
    }

    public StatQuery keyword(String keyword) {
        this.keyword = keyword;
        return this;
    }

    public StatQuery declareds(Map<String, Declared> declareds) {
        this.declareds = declareds;
        return this;
    }

    public StatQuery searcheds(Map<String, Searched> searcheds) {
        this.searcheds = searcheds;
        return this;
    }

    public StatQuery dataPermised(List<Map<String, Searched>> dataPermised) {
        this.dataPermised = dataPermised;
        return this;
    }
}
